import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import { ProjectApi } from '@/api/dk/project'
// 定义类型
export interface Hazard {
  id: number
  type: number
  cnName: string
  onlyReco?: boolean
  letter?: string
  worker: string[] // 劳动者，改为字符串数组
  contactTiming: string // 接触时机，改为必填
  contactTime?: string
  workContent?: string // 工作内容
  laborIntensity?: string // 工作内容
  source?: string // 来源
  whgroup?: string // 来源
  sampling?: {
    sampleDays: number
    pointCount: number
    sampleCount: number
    contactHours: number
    startDay: number
    timeType: 'long' | 'short'
    sampleType: 'fix' | 'personal' | 'none'
    isCustomTime?: boolean
    sampleDuration?: number
    flowRate?: string
    strengthType?: number
  }
  contactFrequency?: {
    count: number
    duration: number
    interval: number
  }
  personalProtection?: string
  personalProtectionList?: string[]
  personalProtectionIds?: number[]
  protectiveFacilities?: string
  protectiveFacilitiesList?: string[]
  protectiveFacilitiesIds?: number[]
  fluctuationTime?: string
  remark?: string
  airCollector?: string
  airCollectorList?: string[]
  airCollectorIds?: number[]
  testStandard?: string // 检测依据
  testStandardList?: string[]
  measuringEquipment?: string // 测量设备
  measuringEquipmentList?: string[]
  storageLife?: string // 保存期限
  storageLifeList?: string[]
  workLocation?: string // 工作地点
  mac?: string
  pcTwa?: string
  pcStel: string
  operationType: number
  // 逻辑删除标记：按页面维度
  deletedInPage1?: boolean
  deletedInPage2?: boolean
}

export interface TableItem {
  id: string
  testItem: string
  contactTime: string | undefined
  workContent?: string // 工作内容
  laborIntensity?: string // 劳动强度
  source?: string // 来源
  contactFrequency?: {
    count: number
    duration: number
    interval: number
  }
  fluctuationTime: string
  workLocation: number
  remark: string
  hazards: Hazard[]
  personalProtection: string
  personalProtectionList: string[]
  personalProtectionIds: number[]
  protectiveFacilities: string
  protectiveFacilitiesList: string[]
  protectiveFacilitiesIds: number[]
  sampleMethod: number | undefined
  longShortTime: number | undefined
  sampleDuration: number | undefined
  flowRate: number | undefined
  strengthType: number | undefined
  sampleDays: number | undefined
  sampleCount: number | undefined
  backupCount: number | undefined
  sampleCode: string
  editing?: string
  editingValue?: number | string
  isFirstHazard: boolean
  hazardCount: number
  originalId: string
  // 独立标识符，用于区分不同的行
  rowKey?: string
  sampling?: {
    sampleDays: number
    pointCount: number
    sampleCount: number
    contactHours: number
    startDay: number
    timeType: 'long' | 'short'
    sampleType: 'personal' | 'none'
    isCustomTime?: boolean
    sampleDuration?: number
  }
  operationType?: number // 新增：逻辑删除标记
}

// 工作时段数据结构
export interface WorkTimeSegment {
  id: string
  startTime: string
  endTime: string
  duration: number // 时长（小时）
}

export interface PositionBlock {
  id: string
  name: string
  tableData: TableItem[]
  totalPeople: number
  shiftCount: number
  shiftSystem: string
  workMode: string
  workPosition: string
  workHours: string
  workDays: string
  workStartTime: string | null
  workEndTime: string | null
  workTimeSegments?: WorkTimeSegment[] // 新增：工作时段数组
  workerName?: string[] // 修改：劳动者字段改为字符串数组
  isCustomWorkTime?: boolean
  operationType?: number // 新增：逻辑删除标记
}

export interface TabItem {
  id: string
  name: string
  projectId: string
  isEditing: boolean
  editingName: string
  positions: PositionBlock[]
}

// 定义 store
export const useSurveyStore = defineStore('survey', () => {
  // 状态
  const tabList = ref<TabItem[]>([])
  const activeTab = ref('')
  const route = useRoute()

  // 加载调查数据
  const loadSurveyData = async () => {
    try {
      console.log('=== 开始加载职业卫生调查数据 ===')
      const projectId = route.query.projectId
      if (!projectId) {
        console.error('项目ID不存在')
        return null
      }

      // 调用后端 API 获取数据
      const response = await ProjectApi.getJobSurvey(Number(projectId))
      console.log('从API获取的数据:', response)

      if (response && Array.isArray(response)) {
        // 直接使用返回的数据
        const surveyData = response.map((workshop: any) => {
          console.log('处理车间数据:', workshop)
          return {
            id: workshop.workshopId,
            name: workshop.workshopName,
            projectId: projectId as string,
            isEditing: false,
            editingName: '',
            positions: workshop.positions.map((position: any) => {
              return {
                id: position.positionInfo.id,
                name: position.positionInfo.name,
                totalPeople: position.positionInfo.totalPeople,
                shiftCount: position.positionInfo.shiftCount,
                shiftSystem: position.positionInfo.shiftSystem,
                workMode: position.positionInfo.workMode,
                workPosition: position.positionInfo.workPosition,
                workHours: Number(position.positionInfo.workHours) || 0,
                workDays: Number(position.positionInfo.workDays) || 0,
                workStartTime: position.positionInfo.workStartTime,
                workEndTime: position.positionInfo.workEndTime,
                workTimeSegments: position.positionInfo.workTimeSegments || [], // 新增：加载工作时段数据
                workerName: Array.isArray(position.positionInfo.workerName) ? position.positionInfo.workerName : (position.positionInfo.workerName ? [position.positionInfo.workerName] : []), // 加载劳动者字段为数组
                operationType: position.positionInfo.operationType || false, // operationType 标记是哪个页面的数据 1调查2方案
                tableData: position.testItems.map((item: any, index: number) => {
                  return {
                    id: item.id,
                    rowKey: `${item.id}_${index}_${Date.now()}_${Math.random().toString(36).substring(2, 10)}`, // 添加唯一行键
                    testItem: item.testItem.fullText,
                    contactTime: item.contactTime,
                    workContent: item.workContent || '',
                    laborIntensity: item.laborIntensity ,
                    source: item.source || '',
                    contactFrequency: {
                      count: Number(item.contactFrequency?.count) || 1,
                      duration: Number(item.contactFrequency?.duration) || 1,
                      interval: Number(item.contactFrequency?.interval) || 1
                    },
                    fluctuationTime: item.fluctuationTime,
                    remark: item.remark,
                    workLocation: item.workLocation || 1, // 添加 workLocation，默认为1
                    hazards: item.hazards.map((hazard: any) => {
                      return {
                        id: hazard.id,
                        type: Number(hazard.type) || 0,
                        cnName: hazard.cnName,
                        onlyReco: hazard.onlyReco === true,
                        worker: hazard.worker  ,
                        contactTiming: hazard.contactTiming  ,
                        workContent: hazard.workContent || '',
                        source: hazard.source || '',
                        mac: hazard.mac || '',
                        pcTwa: hazard.pcTwa || '',
                        pcStel: hazard.pcStel || '',
                        operationType: hazard.operationType ,
                        contactTime: hazard.contactTime || item.contactTime,
                        contactFrequency: {
                          count: Number(hazard.contactFrequency?.count) || 1,
                          duration: Number(hazard.contactFrequency?.duration) || 1,
                          interval: Number(hazard.contactFrequency?.interval) || 1
                        },
                        sampling: {
                          sampleDays: Number(hazard.sampleDays) || 0,
                          pointCount: Number(hazard.pointCount) || 0,
                          sampleCount: Number(hazard.sampleCount) || 0,
                          contactHours: Number(hazard.contactTime) || 0,
                          startDay: 1,
                          timeType: hazard.longShortTime || 'long',
                          sampleType: hazard.sampleMethod || 'none',
                          isCustomTime: false,
                          sampleDuration: Number(hazard.sampleDuration) || 0,
                          flowRate: Number(hazard.flowRate) || 0,
                          strengthType: Number(hazard.strengthType) || 0
                        },
                        personalProtection: hazard.personalProtection?.text || '',
                        personalProtectionList: hazard.personalProtection?.list || [],
                        personalProtectionIds: hazard.personalProtection?.ids || [],
                        protectiveFacilities: hazard.protectiveFacilities?.text || '',
                        protectiveFacilitiesList: hazard.protectiveFacilities?.list || [],
                        protectiveFacilitiesIds: hazard.protectiveFacilities?.ids || [],
                        fluctuationTime: item.fluctuationTime, // 从项目层级复制
                        remark: item.remark, // 从项目层级复制
                        airCollector: hazard.airCollector || '',
                        airCollectorList: hazard.airCollectorList || [],
                        airCollectorIds: hazard.airCollectorIds || [],
                        testStandard: hazard.testStandard || '',
                        testStandardList: hazard.testStandardList || [],
                        measuringEquipment: hazard.measuringEquipment || '',
                        measuringEquipmentList: hazard.measuringEquipmentList || [],
                        storageLife: hazard.storageLife || '',
                        storageLifeList: hazard.storageLifeList || [],
                        deletedInPage1: hazard.deletedInPage1 || false,
                        deletedInPage2: hazard.deletedInPage2 || false,
                        workLocation: hazard.workLocation || ''
                      }
                    }),
                    protectiveFacilities: '',
                    sampleMethod: undefined,
                    longShortTime: undefined,
                    sampleDuration: undefined,
                    flowRate: undefined,
                    strengthType: undefined,
                    sampleDays: undefined,
                    sampleCount: undefined,
                    backupCount: undefined,
                    sampleCode: '',
                    isFirstHazard: true,
                    hazardCount: item.hazards.length,
                    originalId: item.id,
                    operationType: item.operationType || false
                  }
                })
              }
            })
          }
        })
        // 更新 tabList
        tabList.value = surveyData
        if (surveyData.length > 0) {
          activeTab.value = surveyData[0].id
        }

        return surveyData
      }
      return null
    } catch (error) {
      return null
    }
  }

  // 打印调查数据
  let lastJobSurveyData = '' // 缓存上一次的参数字符串
  const printSurveyData = () => {
    console.log('=== 开始准备保存数据 ===')

    const surveyData = tabList.value.map((tab) => {
      return {
        projectId: route.query.projectId as string,
        workshopId: tab.id,
        workshopName: tab.name,
        positions: tab.positions.map((position) => {
          return {
            positionInfo: {
              id: position.id,
              name: position.name,
              totalPeople: position.totalPeople,
              shiftCount: position.shiftCount,
              shiftSystem: position.shiftSystem,
              workMode: position.workMode,
              workPosition: position.workPosition,
              workHours: position.workHours.toString(),
              workDays: position.workDays.toString(),
              workStartTime: position.workStartTime,
              workEndTime: position.workEndTime,
              workTimeSegments: position.workTimeSegments || [], // 新增：保存工作时段数据
              workerName: position.workerName || [], // 保存劳动者字段为数组
              operationType: position.operationType  // 保存逻辑删除标记
            },
            testItems: position.tableData.map((item) => {
              // 解析 testItem 中的 workshop-prefix 和实际内容
              const testItemContent = item.testItem.replace(/<[^>]+>/g, '') // 移除所有HTML标签
              const workshopPrefix =
                item.testItem.match(/<span class="workshop-prefix">([^<]+)<\/span>/)?.[1] || ''
              const hazardsData =
                item.hazards?.map((hazard) => {
                  // 构建保存的危害数据 - 特别注意personalProtection和protectiveFacilities的嵌套格式
                  return {
                    id: hazard.id,
                    type: hazard.type.toString(),
                    cnName: hazard.cnName,
                      onlyReco: hazard.onlyReco === true,
                    mac: hazard.mac,
                    pcTwa: hazard.pcTwa,
                    pcStel: hazard.pcStel,
                    worker: hazard.worker || '',
                    operationType: hazard.operationType ,
                    deletedInPage1: hazard.deletedInPage1 === true,
                    deletedInPage2: hazard.deletedInPage2 === true,
                    contactTiming: hazard.contactTiming || '',
                    workContent: hazard.workContent || '',
                    laborIntensity: hazard.laborIntensity || '',
                    source: hazard.source || '',
                    contactTime: item.contactTime || '',
                    contactFrequency: item.contactFrequency || {
                      count: 1,
                      duration: 1,
                      interval: 1
                    },
                    personalProtection: {
                      list: hazard.personalProtectionList || [],
                      ids: hazard.personalProtectionIds || [],
                      text: hazard.personalProtection || ''
                    },
                    protectiveFacilities: {
                      list: hazard.protectiveFacilitiesList || [],
                      ids: hazard.protectiveFacilitiesIds || [],
                      text: hazard.protectiveFacilities || ''
                    },
                    // 采样相关字段修正 - 确保正确保存采样类型
                    sampleMethod: hazard.sampling?.sampleType || 'none',
                    longShortTime: hazard.sampling?.timeType || 'long',
                    sampleDuration: hazard.sampling?.sampleDuration?.toString() || '',
                    flowRate: hazard.sampling?.flowRate?.toString() || '',
                    strengthType: hazard.sampling?.strengthType?.toString() || '',
                    sampleDays: hazard.sampling?.sampleDays?.toString() || '',
                    sampleCount: hazard.sampling?.sampleCount?.toString() || '',
                    pointCount: hazard.sampling?.pointCount?.toString() || '',
                    backupCount: '',
                    sampleCode: item.sampleCode || '',
                    airCollector: hazard.airCollector || '',
                    airCollectorList: hazard.airCollectorList || [],
                    airCollectorIds: hazard.airCollectorIds || [],
                    testStandard: hazard.testStandard || '',
                    testStandardList: hazard.testStandardList || [],
                    measuringEquipment: hazard.measuringEquipment || '',
                    measuringEquipmentList: hazard.measuringEquipmentList || [],
                    storageLife: hazard.storageLife || '',
                    storageLifeList: hazard.storageLifeList || [],
                    workLocation: hazard.workLocation || ''
                  }
                }) || []

              // 确保项目级防护数据格式正确
              const itemPersonalProtectionList = Array.isArray(item.personalProtectionList)
                ? [...item.personalProtectionList]
                : []
              const itemPersonalProtectionIds = Array.isArray(item.personalProtectionIds)
                ? [...item.personalProtectionIds]
                : []
              const itemProtectiveFacilitiesList = Array.isArray(item.protectiveFacilitiesList)
                ? [...item.protectiveFacilitiesList]
                : []
              const itemProtectiveFacilitiesIds = Array.isArray(item.protectiveFacilitiesIds)
                ? [...item.protectiveFacilitiesIds]
                : []

              return {
                id: item.id,
                testItem: {
                  workshopPrefix,
                  content: testItemContent,
                  fullText: item.testItem // 保留原始HTML用于显示
                },
                contactTime: item.contactTime || '',
                workContent: item.workContent || '',
                laborIntensity: item.laborIntensity ,
                source: item.source || '',
                contactFrequency: item.contactFrequency || {
                  count: 1,
                  duration: 1,
                  interval: 1
                },
                fluctuationTime: item.fluctuationTime || '',
                remark: item.remark || '',
                workLocation: item.workLocation, // 添加 workLocation 字段
                // 添加项目级别的防护数据
                personalProtection: {
                  list: itemPersonalProtectionList,
                  ids: itemPersonalProtectionIds,
                  text: item.personalProtection || ''
                },
                protectiveFacilities: {
                  list: itemProtectiveFacilitiesList,
                  ids: itemProtectiveFacilitiesIds,
                  text: item.protectiveFacilities || ''
                },
                hazards: hazardsData.map(hazard => ({
                  ...hazard,
                  contactFrequency: hazard.contactFrequency || {
                    count: 1,
                    duration: 1,
                    interval: 1
                  }
                })),
                operationType: item.operationType
              }
            })
          }
        })
      }
    })
    const data = {
      jobSurvey: surveyData,
      projectId: route.query.projectId
    }

    // 新增：参数对比逻辑
    const dataStr = JSON.stringify(data)
    if (dataStr === lastJobSurveyData) {
      // console.log('参数未变化，不再调用API')
      return surveyData
    }
    lastJobSurveyData = dataStr

    // console.log('开始调用后端API保存数据...{}', JSON.stringify(data))
    ProjectApi.updateJobSurvey(data)
    // ElMessage.success('修改成功')
    return surveyData
  }

  // 更新 tabList
  const updateTabList = (newTabList: TabItem[]) => {
    tabList.value = newTabList
    // 更新后自动保存
    // saveSurveyData()
  }

  // 更新 activeTab
  const updateActiveTab = (newActiveTab: string) => {
    activeTab.value = newActiveTab
    // 更新后自动保存
    // saveSurveyData()
  }

  return {
    // 状态
    tabList,
    activeTab,
    // 方法
    loadSurveyData,
    printSurveyData,
    updateTabList,
    updateActiveTab
  }
})
